import { useState, useEffect, useRef, useContext } from 'react'
import { Table, Form, Button, Input, Modal, message } from 'antd';
import { configContext, getLocalValue } from '../../../config/env'
import commonService from '../../../service/index'
import modal from 'antd/es/modal';
import { ExclamationCircleOutlined } from '@ant-design/icons';

function BroadcastCategory() {
  const [tableData, setData] = useState<any>([])
  const [categoryChannel, setCategoryChannel] = useState<any>([])
  const [channelData, setChannelData] = useState<any>([])
  const [channelTableData, updateChannelData] = useState<any>([])
  const [loading, setLoading] = useState(true)
  const [param, setParam] = useState({
    id: ''
  })
  const [form, setForm] = useState({
    op: 3,
    op_param1: '',
    op_param2: ''
  })
  const [dataItem, setDataItem] = useState<any>({})
  const [showModal, setModalValue] = useState(false)
  const [showCategoryModal, updateCategoryModal] = useState(false)
  const [channelModal, setChannelModal] = useState(false)
  const [height, setHeight] = useState(600)
  const tableRef = useRef<any>()
  const localValue = useContext(configContext)

  useEffect(() => {
    getData()
    getChannelData()
    getCategoryChannel()
    if (tableRef.current && tableRef.current.offsetHeight) {
      setHeight(tableRef.current.offsetHeight)
    }
  }, [])

  const getData = async () => {
    setData([])
    setLoading(true)
    const data:any = await commonService.getBroadcastCategory({
      or: '(type.eq.root,type.eq.channel)'
    })
    setLoading(false)
    if (data) {
      setData(param.id ? data.filter((item: any) => item.category_id == param.id) : data)
    }
  }

  const getCategoryChannel = async () => {
    const data:any = await commonService.getCategoryChannel({})
    if (data) {
      setCategoryChannel(data)
    }
  }

  const getChannelData = async () => {
    const data:any = await commonService.getChannelData({})
    if (data) {
      setChannelData(data)
    }
  }
  
  const getParamValue = (e:any, type:string) => {
    setParam({
      ...param,
      [type]: e.target.value
    })
  }

  const updateFormValue = (e:any) => {
    setForm({
      ...form,
      op_param1: e.target.value
    })
  }

  const showChannelData = (row: any) => {
    setChannelModal(true)
    updateChannelData([])
    const data = categoryChannel.filter((item: any) => row.category_id == item.category_id)
    const newChannelData = data.map((item: any) => {
      const index = channelData.findIndex((context: any) => context.id == item.id)
      if (index >= 0) {
        return {
          ...item,
          ...channelData[index]
        }
      } else {
        return {
          ...item
        }
      }
    })
    updateChannelData(newChannelData)
  }

  const handleCreateCategory = async () => {
    const data:any = await commonService.updateCategoryData(form)
    if (!data.message) {
      message.success('添加分类成功')
      setModalValue(false)
      getData()
    } else {
      message.error(data.message)
    }
  }

  const handleUpdateCateory = async () => {
    const data:any = await commonService.updateCategoryData({
      op: 1,
      op_param1: dataItem.category_id,
      op_param2: dataItem.title
    })
    if (!data.message) {
      message.success('修改分类成功')
      updateCategoryModal(false)
      getData()
    } else {
      message.error(data.message)
    }
  }

  const handleDeleteCategory = (row: any) => {
    modal.confirm({
      title: getLocalValue(localValue, '提示','tip'),
      icon: <ExclamationCircleOutlined />,
      content: getLocalValue(localValue, '确定要删除当前分类?','Whether to delete the current category?'),
      okText: getLocalValue(localValue, '确认','confirm'),
      cancelText: getLocalValue(localValue, '取消','cancel'),
      onOk: async () => {
        const data:any = await commonService.updateCategoryData({
          op:2,
          op_param1: row.category_id,
          op_param2: ''
        })
        if (!data.message) {
          message.success('删除分类成功')
        } else {
          message.error(data.message)
        }
      }
    });
  }

  const handleDeleteChannel = async (row: any) => {
    const data:any = await commonService.updateCategoryData({
      op: 5,
      op_param1: row.id,
      op_param2: row.category_id
    })
    if (!data.message) {
      message.success('删除频道成功')
      updateChannelData(channelTableData.filter((item: any) => item.id != row.id))
      getChannelData()
      getCategoryChannel()
    } else {
      message.error(data.message)
    }
  }


  return ( 
     <div className='table-content' ref={tableRef}>
       <div className='title'>{getLocalValue(localValue, '直播分类','Live stream classification')}</div>
       <div className='table'>
        <div className='form'>
        <Form layout='inline'>
          <Form.Item label={getLocalValue(localValue, '分类ID','category ID')}>
            <Input style={{width: 200}} value={param.id} allowClear onChange={(e) => getParamValue(e, 'id')} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getData}>{getLocalValue(localValue, '查询','query')}</Button>
            <Button type="primary" onClick={() => {setModalValue(true); setForm({...form, op_param1: ''})}} style={{marginLeft: '10px'}}>{getLocalValue(localValue, '添加分类','add category')}</Button>
          </Form.Item>
        </Form>
        </div>
        <Table loading={loading} dataSource={tableData} pagination={false} scroll={{y: height - 200}} rowKey='category_id' columns={
          [{
            title: getLocalValue(localValue, '分类ID','category ID'),
            dataIndex: 'category_id',
            width: 200
          },
          {
            title: getLocalValue(localValue, 'parent_id','parent_id'),
            dataIndex: 'parent_id',
            width: 100
          },
          {
            title: getLocalValue(localValue, 'title','title'),
            dataIndex: 'title',
            width: 200
          },
          {
            title: 'type',
            dataIndex: 'type',
            width: 90
          },
          {
            title: 'path',
            dataIndex: 'path',
            width: 200
          },
          {
            title: getLocalValue(localValue, '图标','icon'),
            dataIndex: 'photo_uri',
            width: 190,
          },
          {
            title: 'apk_root_id',
            dataIndex: 'apk_root_id',
            width: 130
          },
          {
            title: getLocalValue(localValue, '操作','action field'),
            width: 230,
            render: (row) => {
              return <div>
                <Button type="link" onClick={() => {handleDeleteCategory(row)}}>{getLocalValue(localValue, '删除','delete')}</Button>
                <Button type="link" onClick={() => {updateCategoryModal(true);setDataItem(row)}}>{getLocalValue(localValue, '修改','update')}</Button>
                <Button type="link" onClick={() => {showChannelData(row)}}>{getLocalValue(localValue, '查看频道','view channel')}</Button>
              </div>
            }
          }]
        } ></Table>
       </div>

       <Modal title={getLocalValue(localValue, '添加直播分类', 'add category')} width={600} open={showModal} maskClosable={false}	 okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleCreateCategory} onCancel={() => {setModalValue(false) }} >
          <Form layout='inline' labelCol={{span: 3}}>
            <Form.Item label={getLocalValue(localValue, '分类路径', 'channel ID')} style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} value={form.op_param1} allowClear onChange={(e) => {updateFormValue(e)}} />
            </Form.Item>
          </Form>
       </Modal>

       <Modal title={getLocalValue(localValue, '修改直播分类名称', 'update category')} width={600} open={showCategoryModal} maskClosable={false}	okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleUpdateCateory} onCancel={() => {updateCategoryModal(false) }} >
          <Form layout='inline' labelCol={{span: 3}}>
            <Form.Item label={getLocalValue(localValue, '分类名称', 'Classification name')} style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} value={dataItem.title} allowClear onChange={(e) => {setDataItem({...dataItem, title: e.target.value})}} />
            </Form.Item>
          </Form>
       </Modal>

       <Modal title={getLocalValue(localValue, '查看直播分类频道', 'view category channel')} width={1000} open={channelModal} maskClosable={false} footer={null}	okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={() => {setChannelModal(false)}} onCancel={() => {setChannelModal(false) }} >
        <Table dataSource={channelTableData} pagination={false} scroll={{y: 600}} rowKey='channel_id' columns={
            [{
              title: 'category_id',
              dataIndex: 'category_id',
              width: 160
            },
            {
              title: getLocalValue(localValue, '频道ID','category ID'),
              dataIndex: 'channel_id',
              width: 90
            },
            {
              title: getLocalValue(localValue, '国家','country'),
              dataIndex: 'country',
              width: 90
            },
            {
              title: getLocalValue(localValue, '语言','language'),
              dataIndex: 'language',
              width: 90
            },
            {
              title: getLocalValue(localValue, '标题','title'),
              dataIndex: 'title',
              width: 130
            },
            {
              title: getLocalValue(localValue, '媒体类型','media type'),
              dataIndex: 'media_type',
              width: 90
            },
            {
              title: getLocalValue(localValue, '图标','icon'),
              dataIndex: 'photo_uri',
              width: 190,
            },
            {
              title: getLocalValue(localValue, '操作','action field'),
              width: 90,
              render: (row) => {
                return <div>
                  <Button type="link" onClick={() => {handleDeleteChannel(row)}}>{getLocalValue(localValue, '删除','delete')}</Button>
                </div>
              }
            }]
          } ></Table>
       </Modal>
     </div>
  )
}

export default BroadcastCategory